package com.library.Filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.library.result.Result;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CaptchaFilter extends OncePerRequestFilter {
    private final RedisTemplate redisTemplate;

    public CaptchaFilter(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        if ("/api/user/login".equals(request.getServletPath()) && "POST".equals(request.getMethod())) {
            String captcha = request.getParameter("captcha");
            String captchaKey = request.getParameter("captchaKey");

            String storedCaptcha = (String)redisTemplate.opsForValue().get("captcha:" + captchaKey);
            if (storedCaptcha == null || !storedCaptcha.equalsIgnoreCase(captcha)) {
                response.setContentType("application/json;charset=UTF-8");
                Result<Object> result = Result.error(401, "验证错误或过期");
                // 将Result返回
                ObjectMapper objectMapper = new ObjectMapper();
                response.getWriter().write(objectMapper.writeValueAsString(result));
                return;
            }
            // 验证通过后删除Redis中的键
            redisTemplate.delete("captcha:" + captchaKey);
        }
        filterChain.doFilter(request, response);
    }
}
